package com.ciaojian.core.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ciaojian.core.model.Member;
import com.ciaojian.core.model.MemberOrder;
import com.ciaojian.core.model.UserMember;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since 2020-09-12
 */
@Mapper
public interface MemberMapper extends BaseMapper<Member> {


    /**
     * 续费会员卡-月份
     *
     * @param userId   /
     * @param memberId /
     * @param month    /
     */
    @Update("UPDATE d_user_member SET due_date = DATE_ADD(due_date, INTERVAL ${month} MONTH) WHERE user_id = #{userId} AND member_id = #{memberId}")
    void addMemBerMonth(Integer userId, Integer memberId, Integer month);

    @Update("UPDATE d_user_member SET due_date = NOW() WHERE member_id = #{memberId} AND user_id = #{userId}")
    void memberExpired(Integer memberId, Integer userId);

    @Select("SELECT COUNT(1) FROM d_user_member WHERE user_id = #{userId} AND member_id = #{memberId} AND due_date > NOW()")
    Integer memberExpiredGreater(Integer userId, Integer memberId);

    /**
     * 新增会员和用户关联
     *
     * @param userMember 用户会员
     */
    void saveUserMember(UserMember userMember);

    /**
     * 保存会员订单
     *
     * @param memberOrder 会员订单
     */
    void saveMemberOrder(MemberOrder memberOrder);


    /**
     * 会员有效期
     *
     * @param id 会员 id
     * @return 有效期 月数
     */
    @Select("SELECT valid FROM d_member WHERE id = #{id}")
    Integer getMemBerValid(Integer id);

    /**
     * 新增会员
     *
     * @param memberOrder 会员订单
     */
    void saveByMemberOrder(MemberOrder memberOrder);

    /**
     * 获取我的会员卡信息
     * 因为遗留问题,所以查询的是折扣优惠力度最大且没过期的会员卡
     *
     * @param userId 用户 id
     * @return 会员卡信息Map
     */
    @Select(" SELECT dum.*, m.discount, m.all_service\n" +
            "        FROM d_user_member AS dum\n" +
            "                     LEFT JOIN d_member AS m ON m.id = dum.member_id\n" +
            "        WHERE due_date > now()\n" +
            "          AND user_id = #{userId}\n" +
            "        ORDER BY m.discount\n" +
            "        LIMIT 1")
    Map<String, Object> getMyMember(@Param("userId") Integer userId);

    /**
     * 查询用户的会员卡
     *
     * @param userId 用户id
     * @return 会员列表
     */
    List<Map<String, Object>> findUserMemberCard(@Param("userId") Integer userId);

}
